package com.ajz.manager.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.PatternMatchUtils;

import com.ajz.common.service.impl.BaseServiceImpl;
import com.ajz.config.jwt.JwtTokenUtil;
import com.ajz.manager.dao.MemberDao;
import com.ajz.manager.entity.Member;
import com.ajz.manager.service.MemberService;

@Service
public class MemberServiceImpl extends BaseServiceImpl<Member, String> implements MemberService {
	@Autowired
	private MemberDao memberDao;
//	@Autowired
//	private AuthenticationManager authenticationManager;
	@Autowired
    private UserDetailsService userDetailsService;
	@Autowired
    private JwtTokenUtil jwtTokenUtil;
    
    
	@Override
	public Member findByLoginName(String loginName) {
		// TODO Auto-generated method stub
		return memberDao.findByLoginName(loginName);
	}

	@Override
    public String login(String username, String password) {
		Member mb = memberDao.findByLoginName(username);
		if(mb != null) {
			BCryptPasswordEncoder bpe = new BCryptPasswordEncoder();
			if(bpe.matches(password, mb.getPassword())) {
				 return jwtTokenUtil.generateToken(username);
			}
		}
		 
        return "用户名或密码错误";
    }

    @Override
    public String register(Member user) {
        String username = user.getLoginName();
        if (memberDao.findByLoginName(username) != null) {
            return "用户已存在";
        }
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String rawPassword = user.getPassword();
        user.setPassword(encoder.encode(rawPassword));
//        List<String> roles = new ArrayList<>();
//        roles.add("ROLE_USER");
//        user.setRoles(roles);
        memberDao.save(user);
        return "success";
    }

    @Override
    public String refreshToken(String oldToken) {
        String token = oldToken.substring("Bearer ".length());
        if (!jwtTokenUtil.isTokenExpired(token)) {
            return jwtTokenUtil.refreshToken(token);
        }
        return "error";
    }

}
